package ylh.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import ylh.common.R;
import ylh.entity.User;
import ylh.service.UserService;
import ylh.utils.SMSUtils;
import ylh.utils.ValidateCodeUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
@Slf4j 
public class UserController {
    
    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;
    
    /**
     * 发送手机验证码短信
     * @param user
     * @return
     */
    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpSession session){
        String phone = user.getPhone();
        if(!StringUtils.isEmpty(phone)){
            String code = ValidateCodeUtils.generateValidateCode(6).toString();
            log.info("验证码为：{}",code);

            SMSUtils.sendMessage("瑞吉外卖","SMS_461925435", phone,code);
            
//            session.setAttribute(phone, code);
            
            //将生成的验证码缓存到redis中，并且设置有效期为5分钟
            redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);
            RedisConnection connection = redisTemplate.getConnectionFactory().getConnection();
            connection.flushDb();
            return R.success("手机验证码发送成功");
        }
        
        return R.error("短信发送失败");
        
    }
    
    @PostMapping("/login")
    public R<String> login(@RequestBody Map<String,String> map,HttpSession session){
        log.info("手机号和验证码：{},{}",map.get("phone"),map.get("code"));
        String phone = map.get("phone");
        String code = map.get("code");
        //if (session.getAttribute(phone) == null) return R.error("请先发送验证码");
        //Object sessionCode = session.getAttribute(phone);
        
        //从Redis中获取缓存的验证码
        Object sessionCode = redisTemplate.opsForValue().get(phone);
        //判断是否已经发送验证码
        if (sessionCode == null) return R.error("请先发送验证码");
        
        if (code.equals(sessionCode) ){
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getPhone,phone);
            User user = userService.getOne(queryWrapper);
            if (user == null){
                user = new User();
                user.setPhone(phone);
                user.setStatus(1);
                userService.save(user);
            }
            session.setAttribute("user",user.getId());
            
            //如果用户登陆成功，删除Redis中缓存的验证码
            redisTemplate.delete(phone);
            
            return R.success("登陆成功");
        }
        
        return R.error("登陆失败");
    }

    @PostMapping("/loginout")
    public R<String> logout(HttpServletRequest request){
        //清除Session中保存的当前员工的id
        request.getSession().removeAttribute("user");
        return R.success("退出成功");
    }
    
}
